<script setup>
import config from '@/utils/GlobalConfig'

import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import {onMounted, ref} from "vue";
import axios from "axios";

const map = config.map
let curMap = 1
let commonMap = L.layerGroup()
let satelliteMap =L.layerGroup()
// 地图切换
function mapChange(){
  if(curMap === 1){
    curMap =2
    satelliteMap.clearLayers()
    satelliteMap.remove()
     L.tileLayer('http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', { subdomains: "1234" }).addTo(commonMap)
    commonMap.addTo(map)
  }else{
    curMap = 1
    commonMap.clearLayers()
    commonMap.remove()
    L.tileLayer('http://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}', { subdomains: "1234" }).addTo(satelliteMap)
    L.tileLayer('http://webst0{s}.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}', { subdomains: "1234" }).addTo(satelliteMap)
    satelliteMap.addTo(map)

  }
}

import * as turf from '@turf/turf'
// 行政区划
let areaTurf = []
function drawGZQ(){
  axios.get('data/gzq.json').then(res => {
    let data = res.data
    for(let i=0;i<data.features.length;i++){
      areaTurf.push({
        name: data.features[i].properties['地名'],
        turf:turf.polygon(data.features[i].geometry.coordinates)
      })
    }
    // noinspection JSUnusedGlobalSymbols
    let geojson = L.geoJson(data, {
      style: {
        color: '#00daff',
        fillOpacity: 0.1,
        weight: 2
      },
      onEachFeature: onEachFeature
    });
    geojson.addTo(map);

    //为行政区划图层添加鼠标事件
    function onEachFeature(feature, layer) {
      layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight
      });
    }
    let marker
    //高亮颜色
    function highlightFeature(e) {
      let layer = e.target;

      if(layer.feature.properties['地名']!=='' ){
          let polygon = turf.polygon(layer.feature.geometry.coordinates);
          let centroid = turf.centroid(polygon);

          for(let i=0;i<countyOption.value.length;i++){
            if(countyOption.value[i].text ==layer.feature.properties['地名'] ){
              let icon =L.divIcon({
                // iconSize: [30, 30],
                className: "custom",
                html: `<div style="width: 200px;text-align: center;margin-left: -100px;font-size: 16px">${countyOption.value[i].text}(<span style="font-weight: 700">${countyOption.value[i].num})</span></div>`
              })
              marker=L.marker([centroid.geometry.coordinates[1],centroid.geometry.coordinates[0]], {icon}).addTo(map)
            }
          }

        layer.setStyle({
          weight: 4,
          color: '#00daff',
          dashArray: '',
          fillOpacity: 0.7
        });
        if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
          layer.bringToFront();
        }
      }
    }

    //恢复原色
    function resetHighlight(e) {
      geojson.resetStyle(e.target);
      marker.remove()
    }

  })
}

let AllPOI= []
// 获取景区POI

import POI5A from '@/assets/image/5A.png'
import POI4A from '@/assets/image/4A.png'
import POIA from '@/assets/image/1A.png'
import POIHuman from '@/assets/image/human.png'
import POINature from '@/assets/image/nature.png'
import diwenIcon from '@/assets/image/dw.png'
import lishiIcon from '@/assets/image/ls.png'
import shengwuIcon from '@/assets/image/sw.png'
import shuiyuIcon from '@/assets/image/sy.png'
import wenhuaIcon from '@/assets/image/wh.png'
import xiandaiIcon from '@/assets/image/xz.png'
import zongjiaoIcon from '@/assets/image/zj.png'


let typeSta = []  //类型统计饼图
let levelSta = []  //等级统计饼图
let detailtypeSta = []  //详细类型饼图

function getPOI(){

  axios.get(config.webService +'poi').then(e => {
    AllPOI = e.data
    tableData.value = JSON.parse(JSON.stringify(AllPOI.slice(0,6)))
    allTable = AllPOI
    totalNUm.value= AllPOI.length

    let num5A=0
    let num4A=0
    let numA=0
    let humanNum =0
    let natureNum =0

    let detail3={
      diwen:0,
      lishi:0,
      shengwu:0,
      shuiyu:0,
      wenhua:0,
      xiandai:0,
      zongjiao:0
    }


    for(let i=0;i<AllPOI.length;i++) {
      let shopIcon
      if(AllPOI[i].level == '5A'){
        shopIcon = L.icon({
          iconUrl: POI5A,
          iconSize:     [28, 28], // icon的大小
          iconAnchor:   [14, 28], // icon的渲染的位置（相对与marker）
        });
        num5A++
      }else if(AllPOI[i].level == '4A'){
        shopIcon = L.icon({
          iconUrl: POI4A,
          iconSize:     [28, 28], // icon的大小
          iconAnchor:   [14, 28], // icon的渲染的位置（相对与marker）
        });
        num4A++
      }else{
        shopIcon = L.icon({
          iconUrl: POIA,
          iconSize:     [28, 28], // icon的大小
          iconAnchor:   [14, 28], // icon的渲染的位置（相对与marker）
        });
        numA++
      }
      let marker = L.marker([AllPOI[i].lat, AllPOI[i].lon], {icon: shopIcon}).addTo(POILayer1)
      marker.on('click',()=>{
        openDetail(AllPOI[i])
        getEvaluate(AllPOI[i].id)
      })

      // 景区内容
      let shopIcon1
      if(AllPOI[i].type == '人文历史'){
        shopIcon1 = L.icon({
          iconUrl: POIHuman,
          iconSize:     [30, 30], // icon的大小
          iconAnchor:   [15, 30], // icon的渲染的位置（相对与marker）
        });
        humanNum++
      }else if(AllPOI[i].type == '自然风光'){
        shopIcon1 = L.icon({
          iconUrl: POINature,
          iconSize:     [30, 30], // icon的大小
          iconAnchor:   [15, 30], // icon的渲染的位置（相对与marker）
        });
        natureNum++
      }
      let marker1 = L.marker([AllPOI[i].lat, AllPOI[i].lon], {icon: shopIcon1}).addTo(POILayer2)
      marker1.on('click',()=>{
        openDetail(AllPOI[i])
        getEvaluate(AllPOI[i].id)
      })

      // 景区内容
      let shopIcon2
      if(AllPOI[i].detailtype == '地文景观'){
        shopIcon2 = L.icon({
          iconUrl: diwenIcon,
          iconSize:     [24, 24], // icon的大小
          iconAnchor:   [12, 12], // icon的渲染的位置（相对与marker）
        });
        detail3.diwen++
      }else if(AllPOI[i].detailtype == '历史街区'){
        shopIcon2 = L.icon({
          iconUrl: lishiIcon,
          iconSize:     [24, 24], // icon的大小
          iconAnchor:   [12, 12], // icon的渲染的位置（相对与marker）
        });
        detail3.lishi++
      }else if(AllPOI[i].detailtype == '生物景观'){
        shopIcon2 = L.icon({
          iconUrl: shengwuIcon,
          iconSize:     [24, 24], // icon的大小
          iconAnchor:   [12, 12], // icon的渲染的位置（相对与marker）
        });
        detail3.shengwu++
      }else if(AllPOI[i].detailtype == '水域风光'){
        shopIcon2 = L.icon({
          iconUrl: shuiyuIcon,
          iconSize:     [24, 24], // icon的大小
          iconAnchor:   [12, 12], // icon的渲染的位置（相对与marker）
        });
        detail3.shuiyu++
      }else if(AllPOI[i].detailtype == '文化园型'){
        shopIcon2 = L.icon({
          iconUrl: wenhuaIcon,
          iconSize:     [24, 24], // icon的大小
          iconAnchor:   [12, 12], // icon的渲染的位置（相对与marker）
        });
        detail3.wenhua++
      }else if(AllPOI[i].detailtype == '现代人造设施'){
        shopIcon2 = L.icon({
          iconUrl: xiandaiIcon,
          iconSize:     [24, 24], // icon的大小
          iconAnchor:   [12, 12], // icon的渲染的位置（相对与marker）
        });
        detail3.xiandai++
      }else if(AllPOI[i].detailtype == '宗教型'){
        shopIcon2 = L.icon({
          iconUrl: zongjiaoIcon,
          iconSize:     [24, 24], // icon的大小
          iconAnchor:   [12, 12], // icon的渲染的位置（相对与marker）
        });
        detail3.zongjiao++
      }
      let marker2 = L.marker([AllPOI[i].lat, AllPOI[i].lon], {icon: shopIcon2}).addTo(POILayer3)
      marker2.on('click',()=>{
        openDetail(AllPOI[i])
        getEvaluate(AllPOI[i].id)
      })

    }
    levelSta = [{name:'4A以下',value:numA},{name:'5A', value:num5A},{name:'4A',value:num4A}]
    typeSta = [{name:'人文历史', value:humanNum},{name:'自然风光',value:natureNum}]
    detailtypeSta = [{name:'地文景观', value:detail3.diwen},{name:'历史街区', value:detail3.lishi},{name:'生物景观', value:detail3.shengwu}
      ,{name:'水域风光', value:detail3.shuiyu} ,{name:'文化园型', value:detail3.wenhua} ,{name:'现代人造设施', value:detail3.xiandai},{name:'宗教型', value:detail3.zongjiao}]
console.log(detailtypeSta)

  }).catch(e=>{
    console.log(e ,'poi获取失败')
  })
  POILayer1.addTo(map)
  // POILayer2.addTo(map)

}
// 景区列表
let POIPopVisible = ref()
let POIDrawRadio = ref('按景区等级分布')

let POILayer1 = L.layerGroup()  // 按景区等级分布
let POILayer2 = L.layerGroup()  // 按景区内容分布
let POILayer3 = L.layerGroup()  // 按景区类别

function changePOILayer(){
  if(POIDrawRadio.value === '按景区等级分布'){
    POILayer2.removeFrom(map)
    POILayer3.removeFrom(map)
    POILayer1.addTo(map)
  }else if(POIDrawRadio.value === '按景区内容分布'){
    POILayer1.removeFrom(map)
    POILayer3.removeFrom(map)
    POILayer2.addTo(map)
  }else if(POIDrawRadio.value === '按景区类别分布'){
    POILayer1.removeFrom(map)
    POILayer2.removeFrom(map)
    POILayer3.addTo(map)
  }else{
    POILayer1.removeFrom(map)
    POILayer2.removeFrom(map)
    POILayer3.removeFrom(map)
  }
}

// 热力分析
import 'leaflet.heat'
let heatLayer
function addHeatMap(){
  if(heatLayer){
    heatLayer.remove()
    heatLayer=null
    return
  }
  let heatDataList = []
// 构造热力图数据
  AllPOI.forEach((v) => {
    // 纬度、经度、阈值
    let group = [v.lat, v.lon, 1]
    heatDataList.push(group)
  })
// 生成热力图图层，并添加到地图中
  heatLayer = L.heatLayer(heatDataList, {
    radius: 15,
    minOpacity: 0.8,
    gradient: { // 自定义渐变颜色，区间为 0~1 之间(也可以不指定颜色，使用默认颜色)
      '0.2': "#00f",
      '0.3': "#0ff",
      '0.5': "#0f0",
      '0.7': "#ff0",
      '1': "#f00"
    }
  })
  heatLayer.addTo(map);
}

import * as echarts from 'echarts';
import {ElMessage, ElMessageBox} from "element-plus";
// 统计每个县区的景点数量
let areaNum={}
let showChart = ref(false)
function numAnalysis(){
  // showChart.value = !showChart.value
  if(JSON.stringify(areaNum) == "{}"){
    for(let j=0;j<areaTurf.length;j++){
      for(let i=0;i<AllPOI.length;i++) {
        let pt = turf.point([AllPOI[i].lon, AllPOI[i].lat]);
        if(turf.booleanPointInPolygon(pt, areaTurf[j].turf)){
          if(areaNum[areaTurf[j].name]){
            areaNum[areaTurf[j].name] ++
          }else{
            areaNum[areaTurf[j].name] = 1
          }
        }
      }
    }
  }
  let num = []
  let name =[]
  for(let i in areaNum){
    name.push(i)
    num.push(areaNum[i])
  }
  drawEchart(name, num)
  // drawLevelPie()
  // drawTypePie()
}
function drawEchart(name, num){
  var chartDom = document.getElementById('numChart');
  var myChart = echarts.init(chartDom);
  myChart.dispose()
  chartDom = document.getElementById('numChart');
  myChart = echarts.init(chartDom);
  var option = {
    title: {
        left: 'center',
        text: '县域景点数量'
      },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      top: '12%',
      left: '3%',
      right: '8%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: name,
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '数量',
        nameTextStyle:{//轴标题，在xAxis或yAxis根下
          color:'#000',
          fontSize:14
        }
      }
    ],
    dataZoom: [
      {
        type: 'inside'
      }
    ],
    series: [
      {
        name: '数量',
        type: 'bar',
        barWidth: '60%',
        data: num,
        label: {
          show: true,
          position: 'inside'
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        },
      }
    ]
  };

  option && myChart.setOption(option);

}

function drawLevelPie(){
  var chartDom = document.getElementById('numChart');
  var myChart = echarts.init(chartDom);
  myChart.dispose()
  chartDom = document.getElementById('numChart');
  myChart = echarts.init(chartDom);
  var option;
  option = {
    title: {
      left: 'center',
      text: '景点等级统计'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      left: 'left',
      bottom: '1%',
      orient: 'vertical',
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: '80%',
        data: levelSta,
        label: {
          show: true,
          formatter: '{b}: {c}'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  option && myChart.setOption(option);
}

function drawTypePie(){
  var chartDom = document.getElementById('numChart');
  var myChart = echarts.init(chartDom);
  myChart.dispose()
  chartDom = document.getElementById('numChart');
  myChart = echarts.init(chartDom);
  var option;
  option = {
    title: {
      left: 'center',
      text: '景点类别统计'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      left: 'left',
      bottom: '1%',
      orient: 'vertical',
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: '80%',
        data: typeSta,
        label: {
          show: true,
          formatter: '{b}: {c}'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  option && myChart.setOption(option);
}
function drawDetailTypePie(){
  var chartDom = document.getElementById('numChart');
  var myChart = echarts.init(chartDom);
  myChart.dispose()
  chartDom = document.getElementById('numChart');
  myChart = echarts.init(chartDom);
  var option;
  option = {
    title: {
      left: 'center',
      text: '景点类别统计'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      left: 'left',
      bottom: '1%',
      orient: 'vertical',
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: '80%',
        data: detailtypeSta,
        label: {
          show: true,
          formatter: '{b}: {c}'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  option && myChart.setOption(option);
}
// 景区详情
let showDetail=ref(false)
let poiDetail =ref({
  id:'',
  name:'',
  address:'',
  lonlat:'',
  link:'',
  cost:'',
  open_time:'',
  level:'',
  rating:'',
  photos:[],
})
function closeDetail(){
  showDetail.value = false
  poiDetail.value = {
    id:'',
    name:'',
    address:'',
    lonlat:'',
    link:'',
    cost:'',
    open_time:'',
    level:'',
    rating:'',
    photos:[],
  }
}
function openDetail(info){
  if(info.name){
    poiDetail.value.id =info.id
    poiDetail.value.name =info.name
    poiDetail.value.address =info.address
    poiDetail.value.lonlat =info.lon+ ','+ info.lat
    poiDetail.value.link =info.link
    showDetail.value = true
    axios.get('https://restapi.amap.com/v3/place/text?key=ae09534524900d7ff1b3a6d6eb44ea47&keywords=三百山景区').then(e=>{
      if(e.data.info === 'OK' && e.data.pois.length >0){
        poiDetail.value.cost =  e.data.pois[0].biz_ext.cost
        poiDetail.value.open_time =  e.data.pois[0].biz_ext.open_time
        poiDetail.value.level =  e.data.pois[0].biz_ext.level
        poiDetail.value.rating =  e.data.pois[0].biz_ext.rating
        poiDetail.value.photos =  e.data.pois[0].photos
      }
    }).catch(e=>{
      console.log('高德数据获取失败',e)
    })

  }
}

function navigateTo(lonlat){
  window.open('//uri.amap.com/navigation?&to='+ lonlat +',endpoint&&mode=car&policy=0&src=mypage&coordinate=gaode&callnative=0', '_blank');
}

// 获取所有评价信息
let allEvaluateInfo = ref([])
let allWord=['太美了','美不胜收','值得一去','让人陶醉','仙境','历史文化','值得','非常好','干净','整洁','风格独特','艺术','开阔',
'丰富多样','服务好','宾至如归','拥挤','舒适','琳琅满目','过瘾','好吃','传统','艺术','收藏','许多','设计','beauty','beautiful','自然','nature','历史','丰富','赏心悦目',
'很累','一应俱全','游客','喜爱','表演','震撼','合理','爱了']
function getEvaluate(id){
  allEvaluateInfo.value=[]
  axios.get(config.webService+ 'rate/'+ id).then(e=>{
    allEvaluateInfo.value =e.data

    let wordData=[]
    let num = getRandomInt(20,20)
    for(let i=0;i<num;i++){
      wordData.push({
        name:allWord[getRandomInt(0,allWord.length-1)],value:getRandomInt(10,100)
      })
    }
    drawWordCloud(wordData)

  }).catch(e=>{
    console.log('评价信息获取失败',e)
  })

}
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

// 绘制评价词云
import 'echarts-wordcloud';
function drawWordCloud(data){
  // 基于准备好的dom，初始化echarts实例
  var myChart = echarts.init(document.getElementById('word-cloud'));

// 指定图表的配置项和数据
  var option = {
    series: [{
      type: 'wordCloud',
      shape: 'circle',
      keepAspect: false,
      gridSize: 10,
      left: 'center',
      top: 'center',
      width: '98%',
      height: '100%',
      sizeRange: [12, 50],
      rotationRange: [-90, 90],
      // textStyle: {
      //   normal: {
      //     color: function () {
      //       return 'rgb(' +
      //           Math.round(Math.random() * 255) + ',' +
      //           Math.round(Math.random() * 255) + ',' +
      //           Math.round(Math.random() * 255) + ')';
      //     }
      //   },
      //
      // },
      textStyle: {
        fontFamily: 'sans-serif',
        fontWeight: 'bold',
        color: function () {
          return 'rgb(' + [
            Math.round(Math.random() * 160),
            Math.round(Math.random() * 160),
            Math.round(Math.random() * 160)
          ].join(',') + ')';
        },
        emphasis: {
          shadowBlur: 10,
          shadowColor: '#333'
        }
      },
      data: data
    }]
  };

// 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option);
}


// 用户评价信息框
let curUserEvaluate = ref('')
function publishUserEvaluate(id){
  if(!config.isLogin){
    ElMessage({
      message: '请先登录',
      type: 'warning',
    })
    return
  }
  if(curUserEvaluate.value.trim()==''){
    ElMessage({
      message: '请先输入评价信息',
      type: 'warning',
    })
    return
  }
  let evaluate ={
    treeId:id,
    time:getCurDate(),
    user:config.userName,
    content:curUserEvaluate.value.trim()
  }
  axios.post(config.webService+'rate',evaluate).then(() => {
    ElMessage({
      message: '评价成功',
      type: 'success',
    })
    curUserEvaluate.value =''
    getEvaluate(poiDetail.value.id)
  }).catch(e=>{
    console.log('评论失败',e)
  })
}

function getCurDate(){
  const currentTime = new Date();
  const year = currentTime.getFullYear();
  let month = currentTime.getMonth() + 1; // 月份从0开始，因此需要加1
  let day = currentTime.getDate();

  month = month<10 ? '0'+month:month
  day= day<10 ? '0'+day:day
  return year+'-'+month+'-'+day
}

let allTable =[]
let tableData = ref([])
let curPage = ref(1)
let totalNUm = ref(0)

function sizeChange(e){
  tableData.value = allTable.slice((e-1)*6,(e-1)*6+6)
}

let searchValue =ref('')
function searchPOI(){
  levelSelect.value=''
  typeSelect.value=''
  detailtypeSelect.value=''
  countySelect.value =''
  if(searchValue.value ==''){
    ElMessage({
      message: '请输入景区名称',
      type: 'warning',
    })
    return
  }
  allTable=[]
  for(let i=0;i<AllPOI.length;i++){
    if(AllPOI[i].name.indexOf(searchValue.value)!==-1){
      allTable.push(AllPOI[i])
    }
  }
  totalNUm.value = allTable.length
  tableData.value = allTable.slice(0,6)
}
function cancelSearch(){
  allTable=AllPOI
  totalNUm.value = allTable.length
  tableData.value = allTable.slice(0,6)
  searchValue.value =''
  levelSelect.value=''
  typeSelect.value=''
  detailtypeSelect.value=''
  countySelect.value =''
}

// 景区筛选
let levelSelect = ref('')
let levelOption =ref([{ text: '请选择', value: '' },{ text: '5A', value: '5A' },{ text: '4A', value: '4A' },{ text: '4A以下', value: '4A以下' }])
function filterLevel(){
  searchValue.value =''
  allTable=[]
  for(let i=0;i<AllPOI.length;i++){
    if(typeSelect.value=='' && levelSelect.value ==''){
      allTable = AllPOI
      break
    }else if(typeSelect.value=='' && levelSelect.value !=''){
      if(AllPOI[i].level== levelSelect.value){
        allTable.push(AllPOI[i])
      }
    }else if(typeSelect.value !='' && levelSelect.value ==''){
      if(AllPOI[i].type== typeSelect.value){
        allTable.push(AllPOI[i])
      }
    }else{
      if(AllPOI[i].level== levelSelect.value && typeSelect.value == AllPOI[i].type ){
        allTable.push(AllPOI[i])
      }
    }
  }
  //过滤详细类别
  if(detailtypeSelect.value !=''){
    allTable = allTable.filter(v => {
      return v.detailtype == detailtypeSelect.value
    })
  }

  //过滤区县
  if(countySelect.value !=''){
    allTable = allTable.filter(v => {
      return v.county == countySelect.value
    })
  }

  totalNUm.value = allTable.length
  tableData.value = allTable.slice(0,6)
}

// 景区筛选
let typeSelect = ref('')
let typeOption =ref([{ text: '请选择', value: '' },{ text: '自然风光', value: '自然风光' },{ text: '人文历史', value: '人文历史' }])
let detailtypeSelect=ref('')
let detailtypeOption =ref([{ text: '请选择', value: '' },{ text: '地文景观', value: '地文景观' },{ text: '历史街区', value: '历史街区' },{ text: '生物景观', value: '生物景观' },{ text: '水域风光', value: '水域风光' },{ text: '文化园型', value: '文化园型' },{ text: '现代人造设施', value: '现代人造设施' },{ text: '宗教型', value: '宗教型' }])
let countySelect=ref('')
let countyOption =ref([{ text: '请选择', value: '' },{ text: '安远县', value: '安远县' ,num:7},{ text: '崇义县', value: '崇义县',num:4 },{ text: '大余县', value: '大余县',num:4 },
  { text: '定南县', value: '定南县',num:5 },{ text: '赣县区', value: '赣县区',num:14 },{ text: '会昌县', value: '会昌县' ,num:11},{ text: '龙南市', value: '龙南市' ,num:12},{ text: '南康区', value: '南康区',num:9 }
  ,{ text: '宁都县', value: '宁都县' ,num: 7},{ text: '全南县', value: '全南县' ,num: 2},{ text: '瑞金市', value: '瑞金市' ,num:13},{ text: '上犹县', value: '上犹县' ,num:3},{ text: '石城县', value: '石城县' ,num:6},
  { text: '信丰县', value: '信丰县',num: 9 },{ text: '兴国县', value: '兴国县',num:11 },{ text: '寻乌县', value: '寻乌县',num:4 },{ text: '于都县', value: '于都县' ,num:11},{ text: '章贡区', value: '章贡区',num:47 }])

function tableDetail(info){
  map.setView([info.lat,info.lon],16)
  openDetail(info)
  getEvaluate(info.id)

}


let showTable= ref(false)

// 景区统计
let POIStaVisible=ref()

let StaRadio=ref('关闭')
function changeSta(){
  if(StaRadio.value =='按县域统计' ){
    showChart.value= true
    numAnalysis()
  }else if(StaRadio.value =='按景点等级统计' ){
    showChart.value= true
    drawLevelPie()
  }else if(StaRadio.value =='按景区内容统计' ){
    showChart.value= true
    drawTypePie()
  }else if(StaRadio.value =='按景区类别统计' ){
    showChart.value= true
    drawDetailTypePie()
  }else{
    showChart.value = false
  }
}



//年均流量统计
let showllChart=ref(false)
function yearLiuLiangsta(id){
  showllChart.value = true
  let data=[]
  for(let i=0;i<AllPOI.length;i++){
    if(id === AllPOI[i].id){
      data=[AllPOI[i].f19,AllPOI[i].f20,AllPOI[i].f21,AllPOI[i].f22,AllPOI[i].f23]
      break
    }
  }
  var chartDom = document.getElementById('llChart');
  var myChart = echarts.init(chartDom);

  var option = {
    grid: {
      top:'3%',
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['2019', '2020', '2021', '2022', '2023']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name:'年均客流量(万)',
        data: data,
        type: 'line',
        smooth: true
      }
    ]
  };

  option && myChart.setOption(option);
}

//景区导航
let navitateWay =ref('关闭')
let navigateInfo =ref([])
function navigateRoute(){
  if(navitateWay.value =='历史文化之旅' ){
    drawNavigateWay('lswh')
    navigateInfo.value=['在这段历史悠久的旅程中，您将深入探索赣州市的丰富历史和灿烂文化。我们将从赣州市中心出发，沉浸在古老的文化氛围中。',
      '首先，我们将参观赣州文庙，这是中国传统文化的重要象征，是儒家文化的殿堂，也是古代文人墨客的聚集地。接着，我们将前往南武当山，这座历史悠久的道教名山，不仅仅是一座山，更是一座历史的见证者，它的每一寸土地都沉淀着岁月的痕迹。',
    '继续我们的旅程，我们将漫步赣州郁孤台历史文化街区，感受古老街巷的韵味，聆听历史的回响。然后，我们将游览江南宋城历史文化旅游区，仿宋建筑和宋代文化的再现，让我们仿佛穿越回了宋朝时期。' ,
    '不可错过的是瑞金共和国摇篮景区，这里是中国革命的发源地，每一寸土地都沁透着革命先烈的热血和奋斗的足迹。最后，我们将结束这段历史文化之旅，驻足赣州市消防主题公园，缅怀消防英雄，感悟历史的厚重。',
    '这是一次穿越历史的旅程，每一个景点都是历史的见证者，带您领略赣州丰富的历史文化底蕴，感受历史的力量与魅力。']
  }else if(navitateWay.value =='乡村休闲之旅' ){
    drawNavigateWay('xcxx')
    navigateInfo.value=['在这段乡村休闲之旅中，您将远离喧嚣的城市，走进赣州市郊的乡村，感受田园风光和宁静生活的美好，体验农耕文化和客家风情的独特魅力。',
        '我们首先踏上南康家居小镇之旅，这是一个充满田园气息和客家文化底蕴的小镇，您可以漫步于古色古香的街巷，领略传统手工艺的精湛技艺，体验农家生活的舒适和惬意。',
      '接着，我们将前往屏山旅游区，这里是一处集自然风光和休闲娱乐于一体的景区，您可以徒步穿越山林，欣赏壮丽的山水景色，也可以参与各种户外运动和娱乐活动，尽情释放身心。',
        '然后，我们将游览双溪农旅乐游园，这是一个以农业观光和休闲度假为主题的乐园，您可以体验农耕文化，亲自参与农事活动，品尝新鲜的农家美食，感受农民的勤劳与智慧。\n',
        '继续我们的行程，我们将来到南门广场，这是一个集购物、美食和休闲于一体的城市广场，您可以品尝当地特色小吃，购买纪念品和特色商品，感受城市与乡村的融合之美。\n',
        '最后，我们将前往五龙客家风情园，这是一个展示客家文化和乡村风情的景区，您可以参观传统客家建筑，了解客家人的生活习俗和文化传统，感受客家人的热情和好客。\n',
        '这段乡村休闲之旅将带您远离城市的喧嚣，走进大自然的怀抱，感受田园生活的美好与惬意，是一次难忘的乡村之旅。'
    ]
  }else if(navitateWay.value =='自然风光之旅' ){
    navigateInfo.value=['在这段充满自然美景的旅程中，您将探索赣州市的壮丽山水和独特地貌，感受大自然的鬼斧神工，领略其无尽的美丽和神秘。\n',
    '我们首先将踏上三百山景区的征程，这里群山叠嶂，峰峦起伏，被誉为“江南山水甲天下”，让您沉浸在壮丽的自然风光之中。接着，我们将来到南山森林公园，漫步于葱郁的树林间，感受大自然的清新气息，放松身心。\n',
        '然后，我们将前往汉仙岩风景名胜区，探索岩洞中的奇妙景观，领略自然雕琢的奇迹。灵山风景区也是我们的必游之地，这里山清水秀，景色宜人，让您流连忘返。天龙山景区则为我们展现了大自然的雄奇壮美，俯瞰山脉，令人心旷神怡。\n',
        '在蓉江新区滨江公园，您将欣赏到清澈的江水和绵延的河岸景色，感受江南水乡的独特韵味。而五龙客家风情园和大畲花乐园则为我们呈现了别样的自然风光和田园风光，让您感受到乡村的宁静与美好。\n',
        '最后，乌仙山寺将是我们这段自然之旅的终点，登山俯瞰，眺望山脉，感受大自然的伟力和神奇。这段旅程将带您穿越自然的美妙世界，领略赣州的山水风光，感受大自然的魅力与神奇。'
    ]
    drawNavigateWay('zrfg')
  }else if(navitateWay.value =='用户自定义' ){
    // navitateLayer.clearLayers()
    // navitateLayer.remove()
    drawZYDWay()
    // navitateLayer.addTo(map)
    navigateInfo.value = []
    DrawLine()

  }else{
    navitateLayer.clearLayers()
    navitateLayer.remove()
    navigateInfo.value = []
  }
}

let navitateLayer = L.layerGroup()
function drawNavigateWay(n){
  navitateLayer.clearLayers()
  navitateLayer.remove()

  axios.get('./data/'+n+'.json').then(e => {
    L.geoJson(e.data, {
      style: {
        color: '#f00',
        weight: 5
      }
    }).addTo(navitateLayer)
  })
  navitateLayer.addTo(map)
}

function drawZYDWay(){
  navitateLayer.clearLayers()
  navitateLayer.remove()
  navitateLayer.addTo(map)

  axios.get(config.webService+'route').then(e => {
    for(let i=0;i<e.data.length;i++){
      L.polyline(JSON.parse(e.data[i].lonlat),
        {
          color: '#f00',
          weight: 5
        }).addTo(navitateLayer)
    }

  })
}

// 绘制线
//线绘画
function DrawLine() {
  var points = []
  var lines = new L.polyline(points)
  var tempLines = new L.polyline([])
  map.on('click', onClick);    //点击地图
  map.on('dblclick', onDoubleClick);

  function onClick(e) {

    points.push([e.latlng.lat, e.latlng.lng])
    lines.addLatLng(e.latlng)
    navitateLayer.addLayer(lines)
    navitateLayer.addLayer(L.circle(e.latlng, { color: '#ff0000', fillColor: 'ff0000', fillOpacity: 1 }))
    map.on('mousemove', onMove)//双击地图

  }
  function onMove(e) {
    if (points.length > 0) {
      let ls = [points[points.length - 1], [e.latlng.lat, e.latlng.lng]]
      tempLines.setLatLngs(ls)
      navitateLayer.addLayer(tempLines)
    }
  }

  function onDoubleClick() {
    L.polyline(points).addTo(navitateLayer)
    lines = new L.polyline(points)
    map.off('mousemove')
    map.off('click')
    map.off('dblclick')

    ElMessageBox.confirm(
        '是否保存该路线',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info',
        }
    ).then(() => {
      axios.post(config.webService+'route',{lonlat:JSON.stringify(points),time:new Date()}).then(() => {
        ElMessage({
          message: '保存成功',
          type: 'success',
        })
        // points = []
      }).catch(e=>{
        console.log('保存失败',e)
      })
    }).catch(() => {})

  }
}


onMounted(()=> {
  mapChange()
  getPOI()
  drawGZQ()
})
</script>

<template>
  <!--  功能按钮-->
  <div class="fun-btn">
    <el-popover :visible="POIPopVisible" placement="bottom" trigger="hover" :width="160">
      <template #reference>
        <el-button type="primary">景区分布</el-button>
      </template>
      <el-radio-group v-model="POIDrawRadio" @change="changePOILayer">
        <el-radio-button label="按景区等级分布" />
        <el-radio-button label="按景区内容分布" />
        <el-radio-button label="按景区类别分布" />
        <el-radio-button label="图层隐藏" />
      </el-radio-group>
    </el-popover>
    <el-button type="primary" @click="showTable =! showTable">景区列表</el-button>

    <el-button type="success" @click="addHeatMap">热力分析</el-button>
    <el-popover :visible="POIStaVisible" placement="bottom" trigger="hover" :width="160">
      <template #reference>
        <el-button type="success" @click="numAnalysis">景区统计</el-button>
      </template>
      <el-radio-group v-model="StaRadio" @change="changeSta">
        <el-radio-button label="按县域统计" />
        <el-radio-button label="按景点等级统计" />
        <el-radio-button label="按景区内容统计" />
        <el-radio-button label="按景区类别统计" />
        <el-radio-button label="关闭" />

      </el-radio-group>
    </el-popover>

    <el-popover :visible="POIStaVisible" placement="bottom" trigger="hover" :width="160">
      <template #reference>
        <el-button type="success" >导游路线</el-button>
      </template>
      <el-radio-group v-model="navitateWay" @change="navigateRoute">
        <el-radio-button label="历史文化之旅" />
        <el-radio-button label="乡村休闲之旅" />
        <el-radio-button label="自然风光之旅" />
        <el-radio-button label="用户自定义" />
        <el-radio-button label="关闭" />
      </el-radio-group>
    </el-popover>

  </div>

  <el-button class="map-change" type="primary" @click="mapChange">地图切换</el-button>

  <!--  图例-->
  <div class="legend">
    <div v-if="POIDrawRadio === '按景区等级分布'">
      <div><img src="@/assets/image/5A.png"  alt=""> 5A景区</div>
      <div><img src="@/assets/image/4A.png" alt=""> 4A景区</div>
      <div><img src="@/assets/image/1A.png" alt=""> 4A以下</div>
    </div>
    <div v-else-if="POIDrawRadio === '按景区内容分布'">
      <div><img src="@/assets/image/nature.png"  alt=""> 自然风光</div>
      <div><img src="@/assets/image/human.png" alt=""> 人文历史</div>
    </div>
    <div v-else-if="POIDrawRadio === '按景区类别分布'">
      <div><img src="@/assets/image/dw.png" style="width: 28px" alt=""> 地文景观</div>
      <div><img src="@/assets/image/ls.png" style="width: 28px" alt=""> 历史街景</div>
      <div><img src="@/assets/image/sw.png" style="width: 28px" alt=""> 生物景观</div>
      <div><img src="@/assets/image/sy.png" style="width: 28px" alt=""> 水域风光</div>
      <div><img src="@/assets/image/wh.png" style="width: 28px" alt=""> 文化园型</div>
      <div><img src="@/assets/image/xz.png" style="width: 28px" alt=""> 现代人造设施</div>
      <div><img src="@/assets/image/zj.png" style="width: 28px" alt=""> 宗教型</div>
    </div>
  </div>


  <!--  charts-->
  <div style="" class="charts" v-show="showChart">
    <div id="numChart" style="width: 500px;height: 300px"></div>
<!--    <div id="levelChart" style="width: 250px;height: 300px"></div>-->
<!--    <div id="typeChart" style="width: 250px;height: 300px"></div>-->
  </div>

  <!--    景区详情-->
  <div class="shopInfo" v-show="showDetail">
    <div style="text-align: right">
      <img src="@/assets/image/UI/close.png" style="width: 24px;padding-right: 6px;cursor: pointer;" alt="" @click="closeDetail">
    </div>
    <el-carousel :interval="3000" :autoplay="false" style="height: 250px">
      <el-carousel-item v-for="(item, index) in poiDetail.photos" :key="index">
        <img :src="item.url" alt="img" style="width: 100%;height: 100%">
      </el-carousel-item>
    </el-carousel>

    <div class="shopInfo-title" >{{poiDetail.name}}
      <el-button type="success" round style="height: 25px;float: right;" @click="yearLiuLiangsta(poiDetail.id)">年均客流量统计</el-button>
    </div>

    <div style="padding-left: 3px;font-size: 14px;">
      <el-row style="font-size: 14px;">
        <el-col :span="14">
          <el-rate
              v-model="poiDetail.rating"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
          />
        </el-col>

        <el-col :span="10" style="line-height: 32px;text-align: right;cursor: pointer">
          <a style="font-size: 16px;color: #007eff;" target="_blank" :href="poiDetail.link">景区详情</a>
          <img src="@/assets/image/UI/toright.png" style="vertical-align: middle;width: 22px;" alt="">
        </el-col>
      </el-row>
    </div>

    <el-divider style="margin: 12px 0 12px 6px;width: calc(100% - 10px);" />

    <div style="padding-left: 6px;font-size: 14px;margin-top: 10px">
      <el-row>
        <el-col :span="12">营业时间
          <el-divider direction="vertical" style="height: 26px;float: right"/>
        </el-col>
        <el-col :span="12">人均价格</el-col>
      </el-row>

      <el-row style="margin-top: -2px">
        <el-col :span="12" style="color: rgb(4 114 255)">
          {{poiDetail.open_time}}
          <el-divider direction="vertical" style="float: right" />
        </el-col>
        <el-col :span="12">￥{{poiDetail.cost}}/人</el-col>
      </el-row>
    </div>

    <div style="padding: 0 6px;font-size: 14px;margin-top: 10px;">
      位于<span style="font-weight: 700">{{poiDetail.address}}</span>
      <el-button type="primary" round style="height: 25px;margin-left: 70%;margin-top: 3px" @click="navigateTo(poiDetail.lonlat)">去这里</el-button>
    </div>
    <el-divider style="margin: 12px 0 12px 6px;width: calc(100% - 10px);" />
<!--    评价信息-->
    <div style="height: calc(100% - 535px);padding: 0 3px 6px 3px;overflow: auto">

      <div style="font-weight: 700;font-size: 16px;color: #007dff;margin-bottom: 6px">
        景点评价
      </div>
<!--      词云-->
      <div style="width: 294px;height: 200px" id="word-cloud"></div>
      <div v-for="item in allEvaluateInfo" :key="item.id">
        <el-row style="padding:0 3px ">
          <el-col :span="12"><div style="font-size: 14px;font-weight: 700">{{item.user}}</div> </el-col>
          <el-col :span="12"><div style="font-size: 14px;text-align: right">{{item.time}}</div></el-col>
        </el-row>
        <div style="color: #00ceff;">
          {{item.content}}
        </div>
        <hr>

      </div>
    </div>
    <el-input
        v-model="curUserEvaluate"
        style="width: 300px;position: absolute;bottom: 0"
        placeholder="请输入您的评价"
    >
      <template #append>
        <el-button @click="publishUserEvaluate(poiDetail.id)">发布</el-button>
      </template>
    </el-input>

  </div>

<!--  景区列表-->
  <div class="infoTable" v-show="showTable">
    <div style="padding-left: 5px">
      <el-input
          v-model="searchValue"
          style="width: 200px"
          placeholder="请输入景区名称"
      >
      </el-input>
      <el-button @click="searchPOI(poiDetail.id)">查询</el-button> <br>

      <el-select v-model="levelSelect" placeholder="景区等级" style="width: 120px;" @change="filterLevel">
        <el-option
            v-for="item in levelOption"
            :key="item.value"
            :label="item.text"
            :value="item.value"
        />
      </el-select>
      <el-select v-model="typeSelect" placeholder="景区类别" style="width: 120px;padding-left: 10px" @change="filterLevel">
        <el-option
            v-for="item in typeOption"
            :key="item.value"
            :label="item.text"
            :value="item.value"
        />
      </el-select>
      <el-select v-model="detailtypeSelect" placeholder="详细类别" style="width: 120px;padding-left: 10px" @change="filterLevel">
        <el-option
            v-for="item in detailtypeOption"
            :key="item.value"
            :label="item.text"
            :value="item.value"
        />
      </el-select>
      <el-select v-model="countySelect" placeholder="县域查询" style="width: 120px;padding-left: 10px" @change="filterLevel">
        <el-option
            v-for="item in countyOption"
            :key="item.value"
            :label="item.text"
            :value="item.value"
        />
      </el-select>

      <el-button @click="cancelSearch()" style="margin-left: 10px">取消</el-button>
    </div>

    <el-table :data="tableData" stripe style="width: 100%" table-layout="fixed" height="280">
      <el-table-column prop="id" label=""  width="50" />
      <el-table-column prop="name" :show-overflow-tooltip="true" label="名称" />

      <el-table-column prop="level" label="景区等级" width="80"/>

      <el-table-column prop="type" label="景区类别" width="80" />
      <el-table-column prop="detailtype" label="详细类别" width="120" />
      <el-table-column prop="county" label="县域" width="100" />

      <el-table-column prop="address" :show-overflow-tooltip="true" label="地址" />

      <el-table-column fixed="right" label="" width="80">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="tableDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-left: 50%;transform: translateX(-50%);">
      <el-pagination
          :total="totalNUm"
          layout="prev, pager, next"
          v-model:current-page="curPage"
          :page-size="6"
          @current-change="sizeChange"
      />

    </div>

  </div>

<!--  年均流量统计-->
  <div style="" class="liuliangcharts" v-show="showllChart">
    <img src="@/assets/image/UI/close.png" style="width: 20px;margin-left: 96%;cursor: pointer;" alt="" @click="showllChart=false">
    <div id="llChart" style="width: 500px;height: 300px"></div>
  </div>

  <div class = 'navigate-info' v-show="navigateInfo.length >0">
    <div style="text-indent: 2em;margin-bottom: 5px" v-for="(item,index) in navigateInfo" :key="index">{{item}}</div>
  </div>
</template>

<style scoped>
.fun-btn{
  position: absolute;
  top: 65px;
  left: 5px;
  z-index: 1;
}

.map-change{
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 1;
}

.legend{
  position: absolute;
  right: 310px;
  bottom: 1px;
  background: white;
  z-index: 1;
  padding: 5px 5px 0 5px;
}

.legend img{
  width: 32px;
  vertical-align: middle;
  margin-bottom: 5px;
}
.charts{
  position:absolute;
  left: 5px;
  bottom: 5px;
  height: 300px;
  z-index: 999;
  background: #fffc;
  padding-top: 5px;
  display: flex;
}

.infoTable{
  position:absolute;
  left: 5px;
  top: 105px;
  width: 680px;
  z-index: 999;
  background: #fff;
  padding-top: 5px
}

.shopInfo{
  position: absolute;
  right: 0;
  height: calc(100% - 60px);
  width: 300px;
  background: white;
  z-index: 9;
  bottom: 0;
}

.shopInfo-title{
  font-size: 17px;
  color: black;
  font-weight: 700;
  padding: 6px;
}
.liuliangcharts{
  position: absolute;
  left: 55%;
  top: 70px;
  z-index: 999;
  background: #fffc;
}

.navigate-info{
  position: absolute;
  top: 80px;
  right: 310px;
  z-index: 999;
  width: 320px;
  background: white;
  border-radius: 10px;
  padding: 10px;
  color: #ff0036;
  box-shadow: 0 0 4px 1px rgba(0, 0, 0, 0.37);
}

</style>